package com.wonyesoft.wuliu.acticity.bargain;

import httptools.HttpJsonTool;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import tools.SD_Finder;

import com.google.gson.reflect.TypeToken;
import com.wonyesoft.wuliu.AppContent;
import com.wonyesoft.wuliu.R;
import com.wonyesoft.wuliu.acticity.UserLoginActivity;
import com.wonyesoft.wuliu.acticity.base.BaseActivity;
import com.wonyesoft.wuliu.api.GagApi;

import javabeen.ReceiveOrderMessageBeen;

import View.ListViewForScrollView;
import View.ListViewForScrollView.ListViewOnItemClick;
import adapter.BargainListAdapter;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author 作者 陈修园
 * @date 创建时间：2015-6-4 下午3:33:16
 * @version 1.0 司机用户议价功能
 * @parameter
 * @since
 * @return
 */
public class BargainActionActivity extends BaseActivity {
	private OrderSoundRecorder orderSoundRecorder;
	private ReceiveOrderMessageBeen receiveOrderMessageBeen;
	private Button receive;
	private Button send;
	private ListViewForScrollView messageListView;
	private AppContent app;
	private List<ReceiveOrderMessageBeen> messageBeens;
	int mReSendTime = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bargain_action);
		app = (AppContent) getApplication();
		MakeFolder();
		orderSoundRecorder = new OrderSoundRecorder(this);
		Intent intent = getIntent();
		Ini();
		receiveOrderMessageBeen = (ReceiveOrderMessageBeen) intent
				.getSerializableExtra("MessageData");
		Log.v("receiveOrderMessageBeen_id-->>",
				"" + receiveOrderMessageBeen.getOrderId());
		receive = (Button) findViewById(R.id.button1);
		send = (Button) findViewById(R.id.button4);
		receive.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent ev) {
				// TODO Auto-generated method stub
				Log.v("还在点击", "还在点击");
				if (ev.getAction() == MotionEvent.ACTION_DOWN) {
					RecoderSound(true);
				}
				if (ev.getAction() == MotionEvent.ACTION_UP) {
					RecoderSound(false);
					OrderMessageSoundexchange("1");
					goNext();
				}
				return false;
			}
		});

		// playButton.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// // TODO Auto-generated method stub
		// PlaySound();
		// }
		// });
		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				OrderMessageSoundexchange("2");
			}
		});
		getMessageForServer();
	}

	private void Ini() {

		TextView head_title = (TextView) findViewById(R.id.head_title);
		ImageView head_left = (ImageView) findViewById(R.id.head_left);
		head_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				BargainActionActivity.this.finish();
			}
		});
		head_title.setText("议价");
		messageListView = (ListViewForScrollView) findViewById(R.id.listViewForScrollView1);

	}
	private void getMessageForServer() {
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("orderId", receiveOrderMessageBeen.getOrderId());
		dataMap.put("userType", "1");
		if (app.userId == null) {
			openActivity(UserLoginActivity.class);
			this.finish();
		}
		dataMap.put("userId", app.userId);
		Type type = new TypeToken<List<ReceiveOrderMessageBeen>>() {
		}.getType();
		HttpJsonTool httpJsonTool = new HttpJsonTool(this);
		httpJsonTool.SetOnLister(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.what == 1) {
					messageBeens = (List<ReceiveOrderMessageBeen>) msg.obj;
					if (messageBeens.size() > 0) {
						iniListView();
					}
					// iniListView();
					// iniListView();
				}
			}
		});
		httpJsonTool.StartWork(dataMap, GagApi.BARGAIN_HISTORY_MESSAGE, type,
				null);
	}

	private void iniListView() {

		// setDataToListView();

		BargainListAdapter bargainListAdapter = new BargainListAdapter(this,
				messageBeens);
		messageListView.setAdapter(bargainListAdapter);
		// messageListView.
		messageListView.setOnItemClickListener(new ListViewOnItemClick() {

			@Override
			public void OnClick(ViewGroup parent, View view, int position,
					Object o) {
				// TODO Auto-generated method stub

				if (messageBeens.get(position).getType().equals("1")) {
					if (messageBeens.get(position).getUrl() != null) {
						HttpJsonTool httpJsonTool = new HttpJsonTool(
								BargainActionActivity.this);
						httpJsonTool.setImageLister(new Handler() {
							@Override
							public void handleMessage(Message msg) {
								// TODO Auto-generated method stub
								super.handleMessage(msg);
								if (msg.what == 1) {
									PlaySound((String) msg.obj);
								}
							}
						});
						String rootpath = SD_Finder.GetPaht();
						if (rootpath == null) {
							Toast.makeText(BargainActionActivity.this,
									"SD卡不存在，无法播放声音", Toast.LENGTH_LONG).show();
							return;
						}
						if (rootpath.length() == 0) {
							Toast.makeText(BargainActionActivity.this,
									"SD卡不存在，无法播放声音", Toast.LENGTH_LONG).show();
							return;
						}
						Log.v("服务器文件路径：", GagApi.BARGAIN_SOUND_FILE_PATH
								+ messageBeens.get(position).getUrl());
						httpJsonTool
								.DownLoadFile(GagApi.BARGAIN_SOUND_FILE_PATH
										+ messageBeens.get(position).getUrl());
					}
				}
			}
		});
	}

	private void OrderMessageSoundexchange(String typ) {

		HashMap<String, String> files = new HashMap<String, String>();
		HttpJsonTool httpJsonTool = new HttpJsonTool(this);
		httpJsonTool.SetOnLister(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.what == 1) {
					// files=null;
					Toast.makeText(BargainActionActivity.this, "你的信息已经发送给货主",
							Toast.LENGTH_LONG).show();
					getMessageForServer();
					EditText editText = (EditText) findViewById(R.id.bargai_cont);
					editText.setText("");
					InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					inputMethodManager.hideSoftInputFromWindow(
							BargainActionActivity.this.getCurrentFocus()
									.getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
				} else {

					String str = (String) msg.obj;
					if (str.equals("订单已更换用户")) {
						Toast.makeText(BargainActionActivity.this,
								"该司机已经被更换，无法与他进行议价,我们将为您分配新的司机", Toast.LENGTH_LONG).show();
						BargainActionActivity.this.finish();
						app.New_Order_Push=true;
					} else {
						Toast.makeText(BargainActionActivity.this,
								(String) msg.obj, Toast.LENGTH_LONG).show();
					}
				}
			}
		});
		String url = "";
		receiveOrderMessageBeen.setType(typ);
		receiveOrderMessageBeen.setSender(app.userId);
		EditText cont = (EditText) findViewById(R.id.bargai_cont);
		receiveOrderMessageBeen.setContent(cont.getText().toString().trim());
		if (typ.equals("1")) {
			if (orderSoundRecorder.GetSonunFileName().length() > 0
					&& orderSoundRecorder.GetSonunFileName() != null) {
				if (new File(orderSoundRecorder.GetSonunFileName()).length() > 1024) {
					files.put("filename", orderSoundRecorder.GetSonunFileName());
					url = GagApi.BARGAIN_WITH_FILE;
					// "http://192.168.1.113:8080/cqtczh/fleets/sendMsgWithFile";
					// http://192.168.1.122:8080/cqtczh/fleets/sendMsgWithOFile

					files.put("filename", orderSoundRecorder.GetSonunFileName());

					Log.v("路径有文件", url);
					httpJsonTool.StartWork(receiveOrderMessageBeen, url, null,
							files);
				}
			} else {
				Toast.makeText(BargainActionActivity.this,
						"您的声音太短请重新录制或者手机没有SD卡", Toast.LENGTH_LONG).show();
				return;
			}
		}
		if (typ.equals("2")) {
			EditText editText = (EditText) findViewById(R.id.bargai_cont);
			String conts = editText.getText().toString().trim();
			if (conts.length() > 0 && cont != null) {
				receiveOrderMessageBeen.setContent(conts);

				url = GagApi.BARGAIN_WTHI_OUT_FILE;
				// "http://192.168.1.113:8080/cqtczh/fleets/sendMsgWithFile";
				Log.v("路径没有文件", url);
				httpJsonTool
						.StartWork(receiveOrderMessageBeen, url, null, null);
			} else {
				Toast.makeText(BargainActionActivity.this, "请输入内容",
						Toast.LENGTH_LONG).show();
			}
		}

		// http://192.168.1.113:8080/cqtczh/fleets/sendMsgWithFile

	}

	private void PlaySound(String path) {
		MediaPlayer mediaPlayer = new MediaPlayer();

		try {
			mediaPlayer.setDataSource(path);
			mediaPlayer.prepare();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mediaPlayer.start();

	}

	private void RecoderSound(boolean flag) {
		if (flag) {
			orderSoundRecorder.StartRecorder();

		} else if (orderSoundRecorder != null) {

			orderSoundRecorder.StopRecorder();
			// orderSoundRecorder.Release();
		} else {
			Toast.makeText(this, "声音录制器为空", Toast.LENGTH_LONG).show();
		}

	}

	public void MakeFolder() {
		String root = SD_Finder.GetPaht();
		if (root != null) {
			// File.separator

			File file = new File(root + GagApi.TCZH_File);
			File TMP = new File(root + GagApi.IMAGE_FILE_PATH);
			File sound = new File(root + GagApi.SOUND_FILE_PATH);
			File file_apk = new File(root + GagApi.FILE_PATH);
			File UploadFile = new File(root + GagApi.UP_LOAD_FILE);
			// msg.obj=mBitmap;
			if (!file.exists()) {
				file.mkdir();
			}
			if (!TMP.exists()) {
				TMP.mkdir();
			}
			if (!sound.exists()) {
				sound.mkdir();
			}
			if (!file_apk.exists()) {
				file_apk.mkdir();
			}
			if (!UploadFile.exists()) {
				try {

					UploadFile.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	protected void goNext() {
		receive.setEnabled(false);
		new CountDownTimer(4 * 1000, 1000) {
			@Override
			public void onFinish() {
				mReSendTime = 2;
				receive.setEnabled(true);
				receive.setText("按住说话");
			}

			@Override
			public void onTick(long arg0) {

				receive.setText("" + mReSendTime--);
			}

		}.start();
	}

}
